const { searchRecord, addRecord, getItems } = require('./utils/feishuAPI');
App({
  globalData: {
    isLogin: false,//当前用户是否登录
    userInfo: {},//用户个人信息
    isClassLogin: false, // 是否获取课程信息
    classInfo: {}, // 课程信息
    goal: {}, // 目标
    classGoal: '',
    organGoal: '',
    week: 5, // 显示周次
    currentWeek: 5, // 当前真实周次
    progress: 0, // 进度
  },

  // 当小程序初始化完成时，会触发 onLaunch（全局只触发一次）。
  onLaunch: function() {
    // Do something initial when launch.
    // 初始化全局数据
    const that = this
    // this.globalData = {
    //   isLogin: false,
    //   userInfo: {},//用户个人信息
    //   classInfo: {}, // 课程信息
    //   goal: {},
    //   week: 5,
    // };
    
    this.updateWeek();
    this.updateTitle();
    const app = getApp()
    this.checkLoginStatus();
  
  },

  // 当小程序启动，或从后台进入前台显示，会触发 onShow。
  onShow: function(options) {
    // Do something when show.
  },
  // 当小程序从前台进入后台，会触发 onHide。
  onHide: function() {
    // Do something when hide.
  },
  // 当小程序发生脚本错误，或者 API 调用失败时，会触发 onError 并带上错误信息。
  onError: function(msg) {
    console.log(msg)
  },

  // 检查是否已经登录
  checkLoginStatus: function() {
    const app = this;
    tt.getStorage({
      key: 'userInfo',
      success(res) {
        if (res.data) {
          console.log("userInfo already exist");
          app.globalData.isLogin = true;
          app.globalData.userInfo = res.data;

          // 更新用户课程信息
          tt.getStorage({
            key: 'classInfo',
            success(res) {
              if (res.data) {
                console.log('class info already exist')
                app.globalData.classInfo = res.data;
                app.globalData.isClassLogin = true;
                console.log(`app: onLaunch: app.globalData.isClassLogin:${app.globalData.isClassLogin}`)
                // app.updateGoal();
              }
            }
          });
        } else {
          console.log("userInfo don't exist");
          app.globalData.isLogin = false;
          app.globalData.userInfo = {};
        }
        app.updateTitle();
      },
      fail() {
        app.globalData.isLogin = false;
        app.globalData.userInfo = {};
        app.updateTitle();
      }
    });

  },

  // 获取周次
  updateWeek: function() {
  },

  // 获取周次目标
  updateGoal: function() {
    const app = getApp()
    const that = this
    const query = {
      filter: {
        "conjunction": "and",
        "conditions": [
          {
            "field_name": '周次',
            "operator": "is",
            "value": [
              app.globalData.week
            ]
          },
          {
            "field_name": '组号',
            "operator": "is",
            "value": [
              app.globalData.classInfo['组号']
            ]
          }
        ]
      }
    };
    searchRecord('目标管理表', query)
    .then((res) => {
      r = getItems('目标管理表', res.data.data.items)
      if (r != 0) {
        app.globalData.goal = r[0]
        console.log(r)
        app.globalData.classGoal = r[0]['课程目标']
        app.globalData.organGoal = r[0]['组织目标']
        console.log(`home: update: app.globalData.isClassLogin:${app.globalData.isClassLogin}`)
        if (app.globalData.isClassLogin) {
          // that.data.goal = app.globalData.goal
          that.data.classGoal = app.globalData.classGoal
          that.data.organGoal = app.globalData.organGoal
        }

        that.setData({
          classGoal: app.globalData.classGoal,
          organGoal: app.globalData.organGoal,
        })
      } else {
        console.log('search fail')
      }
    })
  },
  // 更新小程序标题
  updateTitle: function() {
    const title = this.globalData.isLogin ? 'NK嵌入式课设' : 'NK嵌入式课设（未登录）';
    tt.setNavigationBarTitle({
      title: title,
      success(res) {
        console.log(`setNavigationBarTitle success: ${JSON.stringify(res)}`);
      },
      fail(res) {
        console.log(`setNavigationBarTitle fail: ${JSON.stringify(res)}`);
      }
    });
  }
})